require 'net/http'

scheduler = Rufus::Scheduler.start_new

scheduler.every("2h") do
  url = URI.parse('http://openexchangerates.org/latest.json')
  req = Net::HTTP::Get.new(url.path)
  res = Net::HTTP.start(url.host, url.port) do |http|
    http.request(req)
  end

  latestRates = ActiveSupport::JSON.decode(res.body)

  currencyExchangeRate = CurrencyExchangeRate.new(latestRates["rates"])
  currencyExchangeRate.timestamp = latestRates["timestamp"]
  result = currencyExchangeRate.save

  puts "Save new currency rate: (#{currencyExchangeRate.timestamp}) #{result}"
end